package cn.mimedai.blurlib.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.AnimRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.annotation.UiThread;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import cn.mimedai.blurlib.R;
import cn.mimedai.blurlib.background.Blur;

public class BlurPopWin {
    private RelativeLayout pop_root_layout;
    private View pop_layout;
    private Builder builder;
    private PopupWindow popupWindow;
    private int radius;
    private float touchY;
    private Bitmap localBit;
    private boolean isCaptureFullScreen = true;

    public static final String GRAVITY_BOTTOM = "BOTTOM";
    public static final String GRAVITY_CENTER = "CENTER";

    public BlurPopWin(Builder builder) {
        this.builder = builder;
        builder.blurPopWin = initBlurPopWin(builder);
    }

    @UiThread
    public void show(View view) {
        show(view, false);
    }

    @UiThread
    public void show(View view, boolean isRefresh) {
        if (isRefresh) {
            if (localBit != null && !localBit.isRecycled()) {
                localBit.recycle();
            }
            localBit = getIerceptionScreen();

        } else {
            if (localBit == null) {
                localBit = getIerceptionScreen();
            }
        }

        pop_root_layout.setBackgroundDrawable(new BitmapDrawable(localBit));
        builder.blurPopWin.popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @UiThread
    public void dismiss() {
        if (builder != null && builder.blurPopWin != null) {
            builder.blurPopWin.popupWindow.dismiss();
        }
    }

    /*
    截取屏幕
    * */
    @Nullable
    private Bitmap getIerceptionScreen() {
        // View是你需要截图的View
        View view = builder.activity.getWindow().getDecorView();
        int viewWidth = view.getWidth() <= 0 ? getScreenWidth(builder.activity) : view.getWidth();
        int viewHeight = view.getHeight() <= 0 ? getScreenHeight(builder.activity) : view.getHeight();
        Bitmap b = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_4444);
        view.draw(new Canvas(b));
        Bitmap bitmap = null;
        if (!isCaptureFullScreen) {
            Rect frame = new Rect();
            view.getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            // 获取屏幕长和高
            int width = getScreenWidth(builder.activity);
            int height = getScreenHeight(builder.activity);
            // 去掉标题栏
            bitmap = Bitmap.createBitmap(b, 0, statusBarHeight, width, height - statusBarHeight);
            bitmap = Blur.apply(builder.activity, bitmap, radius);

        } else {
            bitmap = Blur.apply(builder.activity, b, radius);
        }

        if (bitmap != null) {
            return bitmap;
        } else {
            return null;
        }
    }

    public PopupWindow getPopupWindow() {
        return popupWindow;
    }

    public void setCaptureFullScreen(boolean captureFullScreen) {
        this.isCaptureFullScreen = captureFullScreen;
    }

    /*
        初始化
        * */
    @UiThread
    private BlurPopWin initBlurPopWin(final Builder builder) {
        if (builder != null) {
            isCaptureFullScreen = builder.isCaptureFullScreen;
            View rootView = builder.activity.getLayoutInflater().inflate(R.layout.pop_layout, null,
                    false);
            popupWindow = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            pop_root_layout = (RelativeLayout) rootView.findViewById(R.id.pop_root_layout);
            if (builder.content != null) {
                pop_layout = builder.content;
                pop_root_layout.addView(pop_layout);
            }

            if (builder.radius != 0) {
                radius = builder.radius;
            } else {
                radius = 5;
            }
            if (builder.animationStyle != 0) {
                popupWindow.setAnimationStyle(builder.animationStyle);
            }


            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (builder.showAtLocationType.equals(GRAVITY_CENTER)) {
                lp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
            } else {
                lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            }
            pop_layout.setLayoutParams(lp);
            pop_root_layout.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            touchY = motionEvent.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            break;
                        case MotionEvent.ACTION_UP:

                            if (builder.isBackgroundClose) {
                                if (builder.showAtLocationType.equals(GRAVITY_CENTER)) {
                                    if (touchY < pop_layout.getTop()
                                            || touchY > pop_layout.getBottom()) {
                                        popupWindow.dismiss();
                                    }
                                } else if (builder.showAtLocationType.equals(GRAVITY_BOTTOM)) {
                                    if (touchY < pop_layout.getTop()) {
                                        popupWindow.dismiss();
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
        } else {
            throw new NullPointerException("---> BlurPopWin ---> initBlurPopWin --->builder=null");
        }
        pop_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (builder.popupCallback != null) {
                    builder.popupCallback.onClick(BlurPopWin.this);
                }
            }
        });
        return this;
    }

    public static class Builder {

        protected BlurPopWin blurPopWin;
        protected Activity activity;
        protected Context context;
        protected PopupCallback popupCallback;
        protected int radius;
        protected boolean isCancelable;
        //默认不显示XX
        protected boolean isShowClose = false;
        protected boolean isBackgroundClose = true;
        protected String showAtLocationType = GRAVITY_CENTER;
        protected View content;
        private int animationStyle;
        private boolean isCaptureFullScreen = true;

        public Builder(@NonNull Context context) {
            this.activity = (Activity) context;
            this.context = context;
            this.isCancelable = true;
        }

        public Builder onClick(PopupCallback popupCallback) {
            this.popupCallback = popupCallback;
            return this;
        }

        public Builder setRadius(int radius) {
            this.radius = radius;
            return this;
        }

        public Builder setContent(View content) {
            this.content = content;
            return this;
        }

        public Builder setCaptureFullScreen(boolean captureFullScreen) {
            this.isCaptureFullScreen = captureFullScreen;
            return this;
        }

        public Builder setAnimationStyle(@StyleRes @AnimRes int animationStyle) {
            this.animationStyle = animationStyle;
            return this;
        }

        /*
        * 默认居中,手动设置了才在最下面
        * */
        public Builder setshowAtLocationType(int type) {
            if (type == 0) {
                this.showAtLocationType = GRAVITY_CENTER;
            } else if (type == 1) {
                this.showAtLocationType = GRAVITY_BOTTOM;
            }

            return this;
        }

        public Builder setShowCloseButton(@NonNull boolean flag) {
            this.isShowClose = flag;
            return this;
        }

        public Builder setOutSideClickable(@NonNull boolean flag) {
            this.isBackgroundClose = flag;
            return this;
        }

        @UiThread
        public BlurPopWin build() {
            return new BlurPopWin(this);
        }

        @UiThread
        public BlurPopWin show(View view) {
            BlurPopWin blurPopWin = build();
            blurPopWin.show(view);

            return blurPopWin;
        }

    }

    public interface PopupCallback {

        void onClick(@NonNull BlurPopWin blurPopWin);
    }


    public interface OnBlurCompleteListener {

        public void onBlurComplete();
    }

    private int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    private int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
}
